'use client';

import React, { useState, useEffect } from 'react';
import { Box, Typography, Button, Paper, CircularProgress, TextField, Alert } from '@mui/material';

export default function AuthTestPage() {
  const [authInfo, setAuthInfo] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [token, setToken] = useState('');
  const [tokenFromStorage, setTokenFromStorage] = useState('');
  const [testUserId, setTestUserId] = useState('');

  useEffect(() => {
    // 从localStorage获取token
    const storedToken = localStorage.getItem('token');
    if (storedToken) {
      setTokenFromStorage(storedToken);
      setToken(storedToken);
    }
  }, []);

  const checkAuth = async () => {
    setLoading(true);
    setError('');

    try {
      const response = await fetch('/api/check-auth', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      const data = await response.json();
      setAuthInfo(data);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  const testExportResume = async () => {
    setLoading(true);
    setError('');

    try {
      const response = await fetch('/api/resume/export-simple', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ error: `HTTP错误: ${response.status} ${response.statusText}` }));
        throw new Error(errorData.error || `导出失败: ${response.status} ${response.statusText}`);
      }

      // 获取blob数据
      const blob = await response.blob();

      // 创建URL并下载
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `resume_test.docx`;
      document.body.appendChild(a);
      a.click();

      // 清理
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);

      setAuthInfo({ message: '简历导出成功', timestamp: new Date().toISOString() });
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  const createTestUser = async () => {
    setLoading(true);
    setError('');

    try {
      const response = await fetch('/api/create-test-user');

      if (!response.ok) {
        throw new Error(`创建测试用户失败: ${response.status} ${response.statusText}`);
      }

      const data = await response.json();
      setTestUserId(data.userId);
      setAuthInfo(data);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setLoading(false);
    }
  };

  const testDirectExport = () => {
    if (!testUserId) {
      setError('请先创建测试用户');
      return;
    }

    window.open(`/api/resume/export-full?userId=${testUserId}`, '_blank');
  };

  const testBasicExport = () => {
    if (!testUserId) {
      setError('请先创建测试用户');
      return;
    }

    window.open(`/api/resume/export-basic?userId=${testUserId}`, '_blank');
  };

  const saveToken = () => {
    localStorage.setItem('token', token);
    setTokenFromStorage(token);
  };

  return (
    <Box sx={{ maxWidth: 800, mx: 'auto', p: 4 }}>
      <Typography variant="h4" component="h1" gutterBottom>
        授权测试页面
      </Typography>

      <Paper sx={{ p: 3, mb: 4 }}>
        <Typography variant="h6" gutterBottom>
          当前令牌状态
        </Typography>
        <Typography variant="body1" gutterBottom>
          localStorage中的令牌: {tokenFromStorage ? `${tokenFromStorage.substring(0, 20)}...` : '无'}
        </Typography>

        <TextField
          fullWidth
          label="令牌"
          value={token}
          onChange={(e) => setToken(e.target.value)}
          margin="normal"
          variant="outlined"
        />

        <Box sx={{ mt: 2, display: 'flex', gap: 2 }}>
          <Button
            variant="contained"
            onClick={saveToken}
          >
            保存令牌到localStorage
          </Button>

          <Button
            variant="outlined"
            onClick={() => {
              localStorage.removeItem('token');
              setTokenFromStorage('');
            }}
          >
            清除localStorage中的令牌
          </Button>
        </Box>
      </Paper>

      <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 2, mb: 4 }}>
        <Button
          variant="contained"
          onClick={checkAuth}
          disabled={loading}
        >
          {loading ? <CircularProgress size={24} /> : '检查授权状态'}
        </Button>

        <Button
          variant="contained"
          color="secondary"
          onClick={testExportResume}
          disabled={loading}
        >
          {loading ? <CircularProgress size={24} /> : '测试导出简历'}
        </Button>

        <Button
          variant="contained"
          color="success"
          onClick={createTestUser}
          disabled={loading}
        >
          {loading ? <CircularProgress size={24} /> : '创建测试用户'}
        </Button>

        <Button
          variant="contained"
          color="info"
          onClick={testDirectExport}
          disabled={loading || !testUserId}
        >
          {loading ? <CircularProgress size={24} /> : '导出完整简历'}
        </Button>

        <Button
          variant="contained"
          color="warning"
          onClick={testBasicExport}
          disabled={loading || !testUserId}
        >
          {loading ? <CircularProgress size={24} /> : '导出简单简历'}
        </Button>
      </Box>

      {testUserId && (
        <Alert severity="info" sx={{ mb: 3 }}>
          测试用户ID: {testUserId} - 可以直接使用这个ID测试导出功能
        </Alert>
      )}

      {error && (
        <Alert severity="error" sx={{ mb: 3 }}>
          {error}
        </Alert>
      )}

      {authInfo && (
        <Paper sx={{ p: 3 }}>
          <Typography variant="h6" gutterBottom>
            授权信息
          </Typography>
          <pre style={{ overflow: 'auto', background: '#f5f5f5', padding: 16, borderRadius: 4 }}>
            {JSON.stringify(authInfo, null, 2)}
          </pre>
        </Paper>
      )}
    </Box>
  );
}
